package com.example.Controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.Service.impl.ItServiceImpl;
import com.example.Service.impl.UserServiceImpl;
import com.example.util.Result;
import com.example.pojo.Press;
import com.example.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

import java.util.List;


@RestController
@RequestMapping("/it")
public class ItController {

    @Autowired
    private ItServiceImpl itService;

    @Autowired
    private UserServiceImpl userService;

    @PutMapping("/pressById")
    public Result pressById(@RequestParam(required = false) Integer id){
        //判断id是否存在催促表中存在
        if(itService.repeatId(id) != 0){
            //存在
            itService.pressById(id);
        }else {
            //不存在
            itService.addPressById(id);
        }
        return new Result("200","修改成功");
    }

    //获取所有催促信息 ---- 表 press
    @GetMapping("/selectAllPress")
    public Result selectAllPress(){
        List<Press> pressList = itService.selectAllPress();
        return new Result("200","查询成功",pressList);
    }


    //查询IT部门 每个职责的数量
    @GetMapping("/selectDutyCount")
    public Result selectDutyCount() {
         List<User> userList = itService.selectDutyCount();
         return new Result("200","查询成功",userList);
    }

    //it部门导出功能
    //所有任务可以导出 功能
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        List<User> userList = userService.selectAllItInfo();//优化为查询所有it部门的人员

        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("name", "姓名");

        //处理新别 ----> 进入Excel 1为男 2为女
        userList.forEach(user -> {
            String sexStr;
            if(user.getSex() != null && user.getSex().equals("1")){
                sexStr = "男";
            }else if(user.getSex() != null && user.getSex().equals("2")){
                sexStr = "女";
            }else {
                sexStr = "未知";
            }
            user.setSex(sexStr);
        });
        writer.addHeaderAlias("sex", "性别");

        writer.addHeaderAlias("positionName", "职位");

        writer.addHeaderAlias("phone", "手机号");

        writer.addHeaderAlias("createDate", "入门时间");

        writer.addHeaderAlias("dutyName", "职责");


        writer.setOnlyAlias(true);
        writer.write(userList, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("It部门全部人员表", "UTF-8" );

        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream os = response.getOutputStream();

        writer.flush(os);
        writer.close();
    }


}
